package com.sdonkey.score.controller;

import com.sdonkey.score.model.*;
import com.sdonkey.score.service.IAccountCentralService;
import com.sdonkey.score.service.IAdPlacementService;
import com.sdonkey.score.util.StaticVariableUtil;
import com.sdonkey.score.util.SymmetricEncoder;
import com.sdonkey.score.vo.ResultSuccessVo;
import com.sdonkey.score.vo.ResultVo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @title 广告投放模块
 * @author WangHan
 * @email 774576529@qq.com
 * @time 2017/02
 * @version 1.0
 */
@Controller
public class AdPlacementAction {
	
	@Resource
	private IAdPlacementService adPlacementService;
	@Resource
	private IAccountCentralService accountCentralService;
	
       /**
        * 已投放广告
        * @param req
        * @param res
        * @param session
        * @return
        * @throws Exception
        */
		@RequestMapping("/finishPlacementAd")
		@ResponseBody
		public Map<String, Object>   onTheManagement(HttpServletRequest req, HttpServletResponse res, HttpSession session )throws Exception {
			Map<String, Object> model = new HashMap<String, Object>();
			String advId = (String) session.getAttribute("advId");
			System.out.println("正在查询你投放的广告！");
			long start = System.currentTimeMillis();
			List <FinishPlacementAdBean> list = adPlacementService.getPlacementAds(advId);
			long end = System.currentTimeMillis();
			System.out.println("-----------1-----------"+(end-start));
			//查询用户余额
//			Double balance = adPlacementService.getBalanceByAdvId(advId);
			long start2 = System.currentTimeMillis();
			//现在时间
			Date nowTime = new Date();
			//修改
			for (FinishPlacementAdBean finishPlacementAdBean : list) {
				String advertiserBalance = finishPlacementAdBean.getAdvertiserBalance();
				if(advertiserBalance==null){
					finishPlacementAdBean.setAdvertiserBalance("0.0");
					advertiserBalance = "0.0";
				}
				String adId = finishPlacementAdBean.getAdId();
				//给广告的id加密
				String aesEncode = SymmetricEncoder.AESEncode(advId, adId);
				finishPlacementAdBean.setAdId(aesEncode);
				//截止时间
				String endDateTime = finishPlacementAdBean.getEndTime();
				DateFormat fmt =new SimpleDateFormat("yyyy-MM-dd");
				Date endTime = fmt.parse(endDateTime);
				//当前广告余额
				double balance = Double.parseDouble(advertiserBalance);
				//单价
				String channelPrice = finishPlacementAdBean.getChannelPrice();
				if(channelPrice==null){
					finishPlacementAdBean.setChannelPrice("0.0");
					channelPrice = "0.0";
				}
				double price = Double.parseDouble(channelPrice);
				//被投诉状态为0
				if("0".equals(finishPlacementAdBean.getPutStatus())){
					finishPlacementAdBean.setStatus("0");
					adPlacementService.EditPlacmentstatus("0",Integer.parseInt(finishPlacementAdBean.getId()));
				}
				//者钱不够状态为5
				else if(balance-price<0){
					finishPlacementAdBean.setStatus("5");
					//修改渠道的投放状态
					adPlacementService.EditPlacmentstatus("5",Integer.parseInt(finishPlacementAdBean.getId()));
				}
				else if(balance==0.0){
					finishPlacementAdBean.setStatus("5");
					//修改渠道的投放状态
					adPlacementService.EditPlacmentstatus("5",Integer.parseInt(finishPlacementAdBean.getId()));
				}
				//时间过期修改为暂停4
				else if((endTime.getTime()+24*60*60*1000)<nowTime.getTime()){
					finishPlacementAdBean.setStatus("4");
					//修改渠道的投放状态
					adPlacementService.EditPlacmentstatus("4",Integer.parseInt(finishPlacementAdBean.getId()));
				}
				//下架的为不可投放
				else if("0".equals(finishPlacementAdBean.getAdStatus())){
					finishPlacementAdBean.setStatus("2");
					//修改渠道的投放状态
					adPlacementService.EditPlacmentstatus("2",Integer.parseInt(finishPlacementAdBean.getId()));
				}
				//其余状态为1
				else if(!"2".equals(finishPlacementAdBean.getStatus())){
					finishPlacementAdBean.setStatus("1");
					//修改渠道的投放状态
					adPlacementService.EditPlacmentstatus("1",Integer.parseInt(finishPlacementAdBean.getId()));
				}
			}
			
			for (int i = 0; i < list.size(); i++) {
//				String adType = list.get(i).getAdType();
//				String preUrl = "video".equals(adType) ? StaticVariableUtil.SHOW_VIDEO_PRE : StaticVariableUtil.SHOW_IMG_PRE;
				//载体
				if (list.get(i).getPadVersionUrl() != null) {
//					list.get(i).setPadVersionUrl(preUrl+list.get(i).getPadVersionUrl());
					list.get(i).setTerminalType("pad");
				}
				if (list.get(i).getPcVersionUrl() != null) {
//					list.get(i).setPcVersionUrl(preUrl+list.get(i).getPcVersionUrl());
					list.get(i).setTerminalType("pc");
				}
				if (list.get(i).getMobileVersionUrl() != null) {
//					list.get(i).setMobileVersionUrl(preUrl+list.get(i).getMobileVersionUrl());
					list.get(i).setTerminalType("mobile");
				}
				if (list.get(i).getTvVersionUrl() != null) {
//					list.get(i).setTvVersionUrl(preUrl+list.get(i).getTvVersionUrl());
					list.get(i).setTerminalType("tv");
				}
				boolean flg = true;
				//不可投放
				if("0".equals(list.get(i).getAdStatus())){
					list.get(i).setAdStatus("不可投放");
					list.get(i).setStatus("手动下架");
					flg = false;
				}else{
					list.get(i).setAdStatus("可投放");
				}
				//广告下所有渠道的总余额
				Double advertiserBalance = 0.0;
				for (int j = 0; j < list.size(); j++) {
					//同一个广告下的渠道
					if(list.get(i).getAdId().equals(list.get(j).getAdId())){	
						advertiserBalance += Double.valueOf(list.get(j).getAdvertiserBalance());
						if(flg){
	 						if("0".equals(list.get(i).getStatus())||"0".equals(list.get(j).getStatus())){	
	 							list.get(i).setStatus("0");
	 							list.get(j).setStatus("0");
							}else{
								
							}
							
							if("4".equals(list.get(i).getStatus())||"4".equals(list.get(j).getStatus())){
								list.get(i).setStatus("4");
	 							list.get(j).setStatus("4");
							}else{
							}
							
							if("2".equals(list.get(i).getStatus())||"2".equals(list.get(j).getStatus())){
								list.get(i).setStatus("2");
	 							list.get(j).setStatus("2");
							}else{
								
							}
							
							if("1".equals(list.get(i).getStatus())||"1".equals(list.get(j).getStatus())){
								list.get(i).setStatus("1");
	 							list.get(j).setStatus("1");
							}else{
								
							}
						}
					}
				}
				list.get(i).setAdvertiserBalance(advertiserBalance.toString());
			}
			
			for (FinishPlacementAdBean finishPlacementAdBean : list) {
				if("0".equals(finishPlacementAdBean.getStatus())){
					finishPlacementAdBean.setStatus("系统下架");
				}
				if("1".equals(finishPlacementAdBean.getStatus())){
					finishPlacementAdBean.setStatus("投放中");
				}
				if("2".equals(finishPlacementAdBean.getStatus())){
					finishPlacementAdBean.setStatus("手动下架");
				}
				if("4".equals(finishPlacementAdBean.getStatus())){
					finishPlacementAdBean.setStatus("系统下架(时间)");
				}
				if("5".equals(finishPlacementAdBean.getStatus())){
					finishPlacementAdBean.setStatus("系统下架(余额)");
				}
			}
			
			//删除掉重复的数据
			for (int i = 0; i < list.size(); i++) {
				for (int j = 0; j < list.size(); j++) {
					if(list.get(i).getAdId().equals(list.get(j).getAdId())&&!list.get(i).getId().equals(list.get(j).getId())){
						list.remove(j);
					}
				}
			}
			
			
			
			
			
			
			long end2 = System.currentTimeMillis();
			System.out.println("----------2------------"+(end2-start2));
			model.put("beans", list);
			model.put("showVideoPre", StaticVariableUtil.SHOW_VIDEO_PRE);
			model.put("showImgPre", StaticVariableUtil.SHOW_IMG_PRE);
		    return model;
		}
			
			
			
			
			
			
			
			
			
			
			
			
//			for (FinishPlacementAdBean finishPlacementAdBean : list) {
//				String advertiserBalance = finishPlacementAdBean.getAdvertiserBalance();
//				if(advertiserBalance==null){
//					finishPlacementAdBean.setAdvertiserBalance("0.0");
//					advertiserBalance = "0.0";
//				}
//				String adId = finishPlacementAdBean.getAdId();
//				String aesEncode = SymmetricEncoder.AESEncode(advId, adId);
//				finishPlacementAdBean.setAdId(aesEncode);
//				//截止时间
//				String endDateTime = finishPlacementAdBean.getEndTime();
//				DateFormat fmt =new SimpleDateFormat("yyyy-MM-dd");
//				Date endTime = fmt.parse(endDateTime);
//				//当前广告余额
//				double balance = Double.parseDouble(advertiserBalance);
//				//单价
//				String channelPrice = finishPlacementAdBean.getChannelPrice();
//				if(channelPrice==null){
//					finishPlacementAdBean.setChannelPrice("0.0");
//					channelPrice = "0.0";
//				}
//				double price = Double.parseDouble(channelPrice);
//				//判断广告的类型
//				if(finishPlacementAdBean.getPadVersionUrl()!=null){
//					finishPlacementAdBean.setTerminalType("pad");
//				}
//				if(finishPlacementAdBean.getPcVersionUrl()!=null){
//					finishPlacementAdBean.setTerminalType("pc");
//				}
//				if(finishPlacementAdBean.getMobileVersionUrl()!=null){
//					finishPlacementAdBean.setTerminalType("mobile");
//				}
//				if(finishPlacementAdBean.getTvVersionUrl()!=null){
//					finishPlacementAdBean.setTerminalType("tv");
//				}
//				//暂停或者钱不够状态为2
//				if(balance-price<0&&!"0".equals(finishPlacementAdBean.getPutStatus())&&!"0".equals(finishPlacementAdBean.getAdStatus())){
//					finishPlacementAdBean.setStatus("暂停");
//					finishPlacementAdBean.setAdStatus("可投放");
//					//修改渠道的投放状态
//					adPlacementService.EditPlacmentstatus("2",Integer.parseInt(finishPlacementAdBean.getId()));
//				}
//				//下架的为不可投放
//				else if("0".equals(finishPlacementAdBean.getAdStatus())){
//					finishPlacementAdBean.setStatus("暂停");
//					finishPlacementAdBean.setAdStatus("不可投放");
//					//修改渠道的投放状态
//					adPlacementService.EditPlacmentstatus("2",Integer.parseInt(finishPlacementAdBean.getId()));
//				}
//				//时间过期修改为暂停
//				else if(endTime.getTime()<nowTime.getTime()&&!"0".equals(finishPlacementAdBean.getPutStatus())){
//					finishPlacementAdBean.setStatus("暂停");
//					finishPlacementAdBean.setAdStatus("可投放");
//					//修改渠道的投放状态
//					adPlacementService.EditPlacmentstatus("2",Integer.parseInt(finishPlacementAdBean.getId()));
//				}
//				else if("2".equals(finishPlacementAdBean.getStatus())&&!"0".equals(finishPlacementAdBean.getPutStatus())){
//					finishPlacementAdBean.setStatus("暂停");
//					finishPlacementAdBean.setAdStatus("可投放");
//					//修改渠道的投放状态
//					adPlacementService.EditPlacmentstatus("2",Integer.parseInt(finishPlacementAdBean.getId()));
//				}else if(balance==0.0&&!"0".equals(finishPlacementAdBean.getPutStatus())){
//					finishPlacementAdBean.setStatus("暂停");
//					finishPlacementAdBean.setAdStatus("可投放");
//					//修改渠道的投放状态
//					adPlacementService.EditPlacmentstatus("2",Integer.parseInt(finishPlacementAdBean.getId()));
//				}
//				//被投诉状态为0
//				else if("0".equals(finishPlacementAdBean.getPutStatus())){
//					finishPlacementAdBean.setStatus("系统下架");
//					finishPlacementAdBean.setAdStatus("可投放");
//					//修改渠道的投放状态
//					adPlacementService.EditPlacmentstatus("0",Integer.parseInt(finishPlacementAdBean.getId()));
//				}
//				//其余状态为1
//				else{
//					finishPlacementAdBean.setStatus("投放中");
//					finishPlacementAdBean.setAdStatus("可投放");
//					//修改渠道的投放状态
//					adPlacementService.EditPlacmentstatus("1",Integer.parseInt(finishPlacementAdBean.getId()));
//				}
//			}
//			long end2 = System.currentTimeMillis();
//			System.out.println("----------2------------"+(end2-start2));
//			model.put("beans", list);
//		    return model;
//		}
		/**
        * 可以投放广告(图片)的名称，id，图片url
        * @param req
        * @param res
        * @param session
        * @return
        * @throws Exception
        */
		@RequestMapping("/finishPlacementAdByAdvId")
		@ResponseBody
		public Map<String, Object>   onTheManagementByAdvId(HttpServletRequest req, HttpServletResponse res, HttpSession session )throws Exception {
			Map<String, Object> model = new HashMap<String, Object>();
			String advId = (String) session.getAttribute("advId");
			int advid = Integer.valueOf(advId);
			//查出广告主所在的公司和公司图片路径
			TadvertiserNew company = adPlacementService.getCompanyByAdvId(advid);
			String type = "picture";
			List<Tad> list = adPlacementService.getPlacementAdsByAdvId(advId,type);
			model.put("beans", list);
			model.put("companyName", company.getCompanyName());
			model.put("companyLogo", company.getCompanyLogo());
		    return model;
		}
		/**
        * 可以投放广告(视频)的名称，id，图片url
        * @param req
        * @param res
        * @param session
        * @return
        * @throws Exception
        */
		@RequestMapping("/finishVideoAdByAdvId")
		@ResponseBody
		public Map<String, Object>   onTheVideoByAdvId(HttpServletRequest req, HttpServletResponse res, HttpSession session )throws Exception {
			Map<String, Object> model = new HashMap<String, Object>();
			String advId = (String) session.getAttribute("advId");
			int advid = Integer.valueOf(advId);
			//查出广告主所在的公司和公司图片路径
			TadvertiserNew company = adPlacementService.getCompanyByAdvId(advid);
			String type = "video";
			List<Tad> list = adPlacementService.getPlacementAdsByAdvId(advId,type);
			model.put("beans", list);
			model.put("companyName", company.getCompanyName());
			model.put("companyLogo", company.getCompanyLogo());
		    return model;
		}
		/**
        * 查出所有的渠道
        * @param req
        * @param res
        * @param session
        * @return
        * @throws Exception
        */
		@RequestMapping("/finishApprovider")
		@ResponseBody
		public Map<String, Object>   onTheManagementByApprovider(HttpServletRequest req, HttpServletResponse res, HttpSession session )throws Exception {
			Map<String, Object> model = new HashMap<String, Object>();
			List<TadApprovider> list = adPlacementService.getAppprovider();
			model.put("beans", list);
		    return model;
		}
		/**
        * 删除已投放广告（更改广告状态）
        * (删除 : 3)
        * @param req
        * @param res
        * @param session
        * @param advertiserBalance
        * @return
        * @throws Exception
        */
		@RequestMapping(value = "deletePlacementAd" ,method = RequestMethod.POST)
		@ResponseBody
		public ResultVo deletePlacementAd(HttpServletRequest request, HttpServletResponse response, HttpSession session, int id, String adId, Double add) {
			//如果所有的渠道都删除 修改广告状态(0)
			String advId = (String) session.getAttribute("advId");
			//解密adId
			String trueadId = SymmetricEncoder.AESDncode(advId, adId);
			List<FinishPlacementAdBean> list = adPlacementService.getPlIdadId(advId, trueadId,null);
			for (FinishPlacementAdBean finishPlacementAdBean : list) {
				adPlacementService.EditPlacmentstatus("3",Integer.parseInt(finishPlacementAdBean.getId()));
			}
			//查出当前广告主的余额
			Double balance = adPlacementService.getBalanceByAdvId(advId);
			//删除要把广告剩余的余额还给账户
			Double actualBalance = balance + 2*add;
			String FyBalance = actualBalance.toString();
			String FyAdvertiserBalance = add.toString();
			accountCentralService.updateActualBalance(advId, FyAdvertiserBalance, FyBalance);
			//解密adId
			int trueAdId = Integer.parseInt(trueadId);
			adPlacementService.EditAdPlacmentstatus("0", trueAdId);
			return new ResultSuccessVo("删除成功");
		}
		/**
		 * 更改广告投放暂停状态
		 * (1 : 投放     2:暂停)
		 * @param request
		 * @param response
		 * @param id
		 * @param check
		 * @param channelPrice
		 * @return
		 */
		@RequestMapping(value = "updatePlacementAdStatus" ,method = RequestMethod.POST)
		@ResponseBody
		public ResultVo updatePlacementAdStatus(HttpServletRequest request, HttpServletResponse response, HttpSession session, String adId, String check) {
			String advId = (String) session.getAttribute("advId");
			//解密adId
			String trueadId = SymmetricEncoder.AESDncode(advId, adId);
			//判断是投放还是暂停
			if("0".equals(check)){
				List<FinishPlacementAdBean> list = adPlacementService.getPlIdadId(advId, trueadId,"2");
				for (FinishPlacementAdBean finishPlacementAdBean : list) {
					//修改状态
					adPlacementService.EditPlacmentstatus("1", Integer.parseInt(finishPlacementAdBean.getId()));
				}
				return new ResultSuccessVo("投放成功");
			}else{
				List<FinishPlacementAdBean> nList = adPlacementService.getPlIdadId(advId, trueadId, "1");
				for (FinishPlacementAdBean finishPlacementAdBean : nList) {
					//修改状态
					adPlacementService.EditPlacmentstatus("2",Integer.parseInt(finishPlacementAdBean.getId()));
				}
				return new ResultSuccessVo("暂停成功");
			}
		}
		
		/**
		 * 根据 广告id 查看已投放广告
		 * @param request
		 * @param response
		 * @param adId
		 * @return
		 * @throws Exception
		 */
		@RequestMapping(value = "/viewPlacementAd",method = RequestMethod.POST)
		@ResponseBody
		public Map<String, Object> viewAd(HttpServletRequest request, HttpServletResponse response, HttpSession session, String adId) throws Exception  {

			Map<String, Object> model = new HashMap<String, Object>();
			String advId = (String) session.getAttribute("advId");
			//解密adId
			String aesDncode = SymmetricEncoder.AESDncode(advId, adId);
			int trueAdId = Integer.parseInt(aesDncode);
			List<TadPlacement> list = adPlacementService.getPlacementById(advId, trueAdId);
			for (TadPlacement tadPlacement : list) {
				//判断广告的类型
				if(tadPlacement.getPadVersionUrl()!=null){
					tadPlacement.setLastUrl(tadPlacement.getPadVersionUrl());
				}
				if(tadPlacement.getPcVersionUrl()!=null){
					tadPlacement.setLastUrl(tadPlacement.getPcVersionUrl());
				}
				if(tadPlacement.getMobileVersionUrl()!=null){
					tadPlacement.setLastUrl(tadPlacement.getMobileVersionUrl());
				}
				if(tadPlacement.getTvVersionUrl()!=null){
					tadPlacement.setLastUrl(tadPlacement.getTvVersionUrl());
				}
			}
			model.put("beans", list);
			return model;
		}

		   /**
		    * 保存投放广告
		    * @param request
		    * @param response
		    * @param session
		    * @param tadPlacementNew
		    * @return
		    * @throws Exception
		    */
		   @RequestMapping(value = "/savePicturePlacementAd",method= RequestMethod.POST)
			@ResponseBody
			 public Map<String, Object> savePlaceAd(HttpServletRequest request, HttpServletResponse response, HttpSession session, TadPlacementNew tadPlacementNew) throws Exception {
			   Map<String, Object> model = new HashMap<String, Object>();
			   //时间
			   DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			   String startTime = tadPlacementNew.getPlanStart();
			   String endTime = tadPlacementNew.getPlanEnd();
			   //起始地时间
			   Timestamp planStart = new Timestamp(format.parse(startTime).getTime());
			   //截止的时间
			   Timestamp planEnd = new Timestamp(format.parse(endTime).getTime());
			   //广告id
			   String adId = tadPlacementNew.getAdId();
			   //广告总投入
			   BigDecimal releaseAmount = tadPlacementNew.getReleaseAmount();
			   //广告投放单价
			   BigDecimal deliveryPrice = tadPlacementNew.getDeliveryPrice();
			   //渠道的名字
			   String name = tadPlacementNew.getChannelName();
			   String[] channelName = name.split(",");
			   //渠道的图片路径
			   String url = tadPlacementNew.getLogoUrl();
			   String[] logoUrl = url.split(",");
			   //渠道id
			   String appid = tadPlacementNew.getAppId();
			   String[] appId = appid.split(",");
			   //单条渠道总金额
			   String amount = tadPlacementNew.getChannelAmount();
			   String[] channelAmount = amount.split(",");
			   //渠道总金额
			   double channelamount = 0.0;
			   if(!"".equals(name)){
				   for (String channel : channelAmount) {
					   double parseDouble = Double.parseDouble(channel);
					   channelamount += parseDouble;
					   
				   }
			   }
			   BigDecimal channelAmounts = new BigDecimal(channelamount);
			   //用户user_id
			   String advId = (String) session.getAttribute("advId");
			   //单条渠道单价
			   String price = tadPlacementNew.getChannelPrice();
			   String[] channelPrice = price.split(",");
			   //添加时间
			   Date date = new Date();   
		       String strDate = format.format(date);
		       //转换
		       Timestamp creatTime = new Timestamp(format.parse(strDate).getTime());
		       //广告投放剩余的余额(广告总投入-渠道总金额)
		       double releaseMount = releaseAmount.doubleValue();
		       BigDecimal deliveryRemainingAmount = new BigDecimal(releaseMount-channelamount);
		     //添加一条数据t_ad_behavioral_statistics表
		       TadBehavioralStatistics tadBehavioralStatistics = new TadBehavioralStatistics();
		       if(adPlacementService.checkAdBehavioral(adId)==null){
				   tadBehavioralStatistics.setAdId(adId);
				   tadBehavioralStatistics.setUserId(advId);
				   tadBehavioralStatistics.setCreateTime(creatTime);
				   tadBehavioralStatistics.setUpdateTime(creatTime);
		       }else{
				   tadBehavioralStatistics.setAdId("是");
		       }
		       if(!"".equals(name)){
		    	 //账户余额
					 Double balance = adPlacementService.getBalanceByAdvId(advId);
					 String actualBalance = balance.toString();
					 String money = releaseAmount.toString();
					for(int i=0;i<channelName.length;i++){
					   Double channelPrices = Double.parseDouble(channelPrice[i]);
					   //单条渠道
					   BigDecimal channelprice = new BigDecimal(channelPrices);
					   TadPlacement tadPlacement = new TadPlacement();
					   Double channelAmoun = Double.parseDouble(channelAmount[i]);
					   //单条渠道总价钱
					   BigDecimal channelAmouns = new BigDecimal(channelAmoun);
					   tadPlacement.setAdId(adId);tadPlacement.setPlanStart(planStart);tadPlacement.setPlanEnd(planEnd);
					   tadPlacement.setReleaseAmount(releaseAmount);tadPlacement.setDeliveryPrice(deliveryPrice);tadPlacement.setAppId(Integer.parseInt(appId[i]));
					   tadPlacement.setDeliveryConsumeAmount(channelAmounts);tadPlacement.setChannelAmount(channelAmouns);tadPlacement.setDeliveryRemainingAmount(deliveryRemainingAmount);
					   tadPlacement.setChannelName(channelName[i]);tadPlacement.setChannelPrice(channelprice);tadPlacement.setDeliveryCarrier(tadPlacementNew.getDeliveryCarrier());
					   tadPlacement.setPutPrice(tadPlacementNew.getPutPrice());tadPlacement.setCreateTime(creatTime);tadPlacement.setUserId(advId);
					   tadPlacement.setLogoUrl(logoUrl[i]);tadPlacement.setAdvertiserBalance(channelAmouns);tadPlacement.setStatus("1");
					   //添加一条渠道
					   int adid = Integer.parseInt(adId);
					   String status = "1";
//					   Double balance = adPlacementService.getBalanceByAdvId(advId);
					   try {
						int ad = adPlacementService.savePlaceAd(tadPlacement,advId,status,adid,money,actualBalance,tadBehavioralStatistics);
							} catch (Exception e) {
								model.put("check","广告投放失败");
								   return model;
							}
				   }
		       }
			   //判断是否添加了渠道(没添加)
			   if(channelName.length == 1&&channelAmount.length==1&&channelPrice.length==1&&"".equals(name)){
				   BigDecimal deliveryRemainingAm = new BigDecimal(0.0);
				   TadPlacement tadPlacement = new TadPlacement();
				   tadPlacement.setAdId(adId);tadPlacement.setPlanStart(planStart);tadPlacement.setPlanEnd(planEnd);tadPlacement.setChannelAmount(releaseAmount);
				   tadPlacement.setReleaseAmount(releaseAmount);tadPlacement.setDeliveryPrice(deliveryPrice);tadPlacement.setPutPrice(tadPlacementNew.getPutPrice());tadPlacement.setChannelPrice(deliveryPrice);
				   tadPlacement.setAdvertiserBalance(releaseAmount);tadPlacement.setDeliveryCarrier(tadPlacementNew.getDeliveryCarrier());tadPlacement.setDeliveryRemainingAmount(deliveryRemainingAm);tadPlacement.setDeliveryConsumeAmount(releaseAmount);
				   tadPlacement.setCreateTime(creatTime);tadPlacement.setUserId(advId);tadPlacement.setStatus("1");
				   String status = "1";
				   int adid = Integer.parseInt(adId);
				   //账户余额
				   Double balance = adPlacementService.getBalanceByAdvId(advId);
				   String actualBalance = balance.toString();
				   String money = releaseAmount.toString();
				   try {
					int ad = adPlacementService.savePlaceAd(tadPlacement,advId,status,adid,money,actualBalance,tadBehavioralStatistics);
				} catch (Exception e) {
					model.put("check","广告投放失败");
					return model;
				}
			   }
			   model.put("check","广告投放成功");
			   return model;
			}
		   
		   
		   
		   /**
			 * 编辑投放广告
			 * @param request
			 * @param response
			 * @param session
			 * @param tadPlacementNew
			 * @return
			 * @throws Exception
			 */
		   @RequestMapping(value = "/editPicturePlacementAd",method= RequestMethod.POST)
			@ResponseBody
			 public Map<String, Object> editPlaceAd(HttpServletRequest request, HttpServletResponse response, HttpSession session, TadPlacementNew tadPlacementNew) throws Exception {
			   Map<String, Object> model = new HashMap<String, Object>();
			   //时间
			   DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			   String startTime = tadPlacementNew.getPlanStart();
			   String endTime = tadPlacementNew.getPlanEnd();
			   //起始地时间
			   Timestamp planStart = new Timestamp(format.parse(startTime).getTime());
			   //截止的时间
			   Timestamp planEnd = new Timestamp(format.parse(endTime).getTime());
			   //广告id
			   String adId = tadPlacementNew.getAdId();
			   //广告总投入
			   BigDecimal releaseAmount = tadPlacementNew.getReleaseAmount();
			   //修改广告总余额
			   BigDecimal deliveryRemainingAmount = tadPlacementNew.getDeliveryRemainingAmount();
			   //广告投放单价
			   BigDecimal deliveryPrice = tadPlacementNew.getDeliveryPrice();
			   //渠道id
			   String PlacementId = tadPlacementNew.getId();
			   String[] id = PlacementId.split(",");
			   //渠道的名字
			   String name = tadPlacementNew.getChannelName();
			   String[] channelName = name.split(",");
			   //渠道的图片路径
			   String url = tadPlacementNew.getLogoUrl();
			   String[] logoUrl = url.split(",");
			   //渠道外键对应id(名字)
			   String appid = tadPlacementNew.getAppId();
			   String[] appId = appid.split(",");
			   //单条渠道总金额
			   String amount = tadPlacementNew.getChannelAmount();
			   String[] channelAmount = amount.split(",");
			   //添加渠道总金额
			   double placementAmount = 0.0;
			   for(int i=0;i<id.length;i++){
				   if("1".equals(id[i])&&id[i]!=null){
					   double parseDouble = Double.parseDouble(channelAmount[i]);
					   placementAmount += parseDouble;
				   }
			   }
			   //实际广告余额(修改之后的广告余额-添加渠道总金额)
			   double actual = deliveryRemainingAmount.doubleValue()-placementAmount;
			   BigDecimal actualPlacement = new BigDecimal(actual);
			   //渠道总金额
			   double channelamount = 0.0;
			   if(!"".equals(name)){
				   for (String channel : channelAmount) {
					   double parseDouble = Double.parseDouble(channel);
					   channelamount += parseDouble;
					   
				   }
			   }
			   BigDecimal channelAmounts = new BigDecimal(channelamount);
			   //用户user_id
			   String advId = (String) session.getAttribute("advId");
			   //单条渠道单价
			   String price = tadPlacementNew.getChannelPrice();
			   String[] channelPrice = price.split(",");
			   //修改时间
			   Date date = new Date();   
		       String strDate = format.format(date);
		       //转换
		       Timestamp updateTime = new Timestamp(format.parse(strDate).getTime());
		       String money = null;
		       //判断是修改还是添加
		       BigDecimal releasemount = null;
		       double releaseamount = 0.0;
		       //成本
		       String putPrice = null;
		       TadPlacement placement = adPlacementService.getPlacementByid(advId, Integer.parseInt(id[0]));
			   putPrice = placement.getPutPrice();
			   //广告总投入(广告总投入+原来广告余额-现在广告余额)
			   double doubleAdValue = releaseAmount.doubleValue();
			   //原来广告余额
			   double deliveryValue = deliveryRemainingAmount.doubleValue();
			   //现在广告余额
			   double RemainingValue = placement.getDeliveryRemainingAmount().doubleValue();
			   releaseamount = doubleAdValue + deliveryValue - RemainingValue;
			   Double Plmoney = deliveryValue - RemainingValue;
			   money = Plmoney.toString();
			   //数据库中的余额
			   BigDecimal advertiserBalance = placement.getAdvertiserBalance();
			   //广告总金额
			   releasemount = new BigDecimal(releaseamount);
			   //计算现在的余额
			   double adeverBalance =  advertiserBalance.doubleValue() + deliveryRemainingAmount.doubleValue();
			   //判断这条数据状态以及是否存在以免发生脏读
			   String checkStatus = placement.getStatus();
			   if("3".equals(checkStatus)){
				   model.put("check","广告已删除请刷新页面");
				   return model;
			   }
		       for(int i=0;i<id.length;i++){
				   if(!"1".equals(id[i])&&id[i]!=null){
					   //修改啊
					   if("".equals(name)||name==null){
						   TadPlacement tadPlacement = new TadPlacement();
						   tadPlacement.setId(Integer.parseInt(id[i]));
						   tadPlacement.setPlanStart(planStart);tadPlacement.setPlanEnd(planEnd);tadPlacement.setUpdateTime(updateTime);
						   tadPlacement.setReleaseAmount(releasemount);tadPlacement.setDeliveryPrice(deliveryPrice);tadPlacement.setDeliveryRemainingAmount(new BigDecimal(0.0));
						   tadPlacement.setDeliveryConsumeAmount(releasemount);tadPlacement.setChannelAmount(releasemount);tadPlacement.setAdvertiserBalance(new BigDecimal(adeverBalance));
						   int editPlacment = adPlacementService.EditPlacment(tadPlacement);
						   if(editPlacment == 0){
							   model.put("check","广告投放失败");
							   return model;
						   }
					   }else{
					   TadPlacement tadPlacement = new TadPlacement();
					   tadPlacement.setId(Integer.parseInt(id[i]));tadPlacement.setChannelAmount(null);
					   tadPlacement.setPlanStart(planStart);tadPlacement.setPlanEnd(planEnd);tadPlacement.setUpdateTime(updateTime);
					   tadPlacement.setReleaseAmount(releasemount);tadPlacement.setDeliveryPrice(deliveryPrice);tadPlacement.setDeliveryRemainingAmount(actualPlacement);
					   tadPlacement.setDeliveryConsumeAmount(channelAmounts);
					   int editPlacment = adPlacementService.EditPlacment(tadPlacement);
					   if(editPlacment == 0){
						   model.put("check","广告投放失败");
						   return model;
					   }
					   }
				   }else{
					   //添加
					   Double channelPrices = Double.parseDouble(channelPrice[i]);
					   //单条渠道
					   BigDecimal channelprice = new BigDecimal(channelPrices);
					   Double channelAmoun = Double.parseDouble(channelAmount[i]);
					   //单条渠道总价钱
					   BigDecimal channelAmouns = new BigDecimal(channelAmoun);
					   TadPlacement tadPlacement = new TadPlacement();
					   tadPlacement.setAdId(adId);tadPlacement.setPlanStart(planStart);tadPlacement.setPlanEnd(planEnd);
					   tadPlacement.setReleaseAmount(releasemount);tadPlacement.setDeliveryPrice(deliveryPrice);tadPlacement.setAppId(Integer.parseInt(appId[i]));
					   tadPlacement.setDeliveryConsumeAmount(channelAmounts);tadPlacement.setChannelAmount(channelAmouns);tadPlacement.setDeliveryRemainingAmount(actualPlacement);
					   tadPlacement.setChannelName(channelName[i]);tadPlacement.setChannelPrice(channelprice);tadPlacement.setDeliveryCarrier("pad");
					   tadPlacement.setPutPrice(putPrice);tadPlacement.setCreateTime(updateTime);tadPlacement.setUserId(advId);
					   tadPlacement.setLogoUrl(logoUrl[i]);tadPlacement.setAdvertiserBalance(channelAmouns);tadPlacement.setStatus("1");
					 //添加一条渠道
					   int adid = Integer.parseInt(adId);
					   String status = "1";
//					   Double balance = adPlacementService.getBalanceByAdvId(advId);
					   int ad = adPlacementService.savePlacementAd(tadPlacement,advId,status,adid);
					   if(ad == 0){
						   model.put("check","广告编辑失败");
						   return model;
					   }
				   }
			   }
		       	//账户余额
				 Double balance = adPlacementService.getBalanceByAdvId(advId);
				 String actualBalance = balance.toString();
				 int plancementBalance = accountCentralService.updateActualBalance(advId, money, actualBalance);
				 if(plancementBalance == 0){
					   model.put("check","广告编辑失败");
					   return model;
				   }
			   model.put("check","广告编辑成功");
			   return model;
			}
}
